package leetcode146

type LRUCache struct {
	data     map[int]int
	keys     []int
	capacity int
}

func Constructor(capacity int) LRUCache {
	return LRUCache{
		data:     make(map[int]int, capacity),
		keys:     make([]int, 0),
		capacity: capacity,
	}
}

func (this *LRUCache) Get(key int) int {
	if _, ok := this.data[key]; ok {
		this.FreshKey(key)
		return this.data[key]
	} else {
		return -1
	}
}

func (this *LRUCache) Put(key int, value int) {
	if _, ok := this.data[key]; ok {
		this.data[key] = value
		this.FreshKey(key)
		return
	}

	if len(this.keys) == this.capacity {
		oldKey := this.keys[0]
		delete(this.data, oldKey)
		this.keys = this.keys[1:]
		this.keys = append(this.keys, key)
		this.data[key] = value
	} else {
		this.keys = append(this.keys, key)
		this.data[key] = value
	}
}

func (this *LRUCache) FreshKey(key int) {
	for i := range this.keys {
		if this.keys[i] == key {
			this.keys = append(this.keys[:i], append(this.keys[i+1:], key)...)
			break
		}
	}
}
